package dao.concret;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import dao.AbstractTable;
import dao.DAO;
import dao.tables.RESPONSABILITE;

public class ResponsabiliteDAO extends DAO<RESPONSABILITE> {

	@Override
	public RESPONSABILITE find(long id) {
		RESPONSABILITE resp = new RESPONSABILITE();
		try {
			Statement stmt = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
				ResultSet.CONCUR_UPDATABLE);
			ResultSet result = stmt
				.executeQuery("SELECT * FROM RESPONSABILITE WHERE idresponsabilite = " + id);
			if (result.first()) resp = new RESPONSABILITE(id, result.getString("responsabilite"));
			result.close();
			stmt.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return resp;
	}

	@Override
	public RESPONSABILITE create(AbstractTable at) {
		RESPONSABILITE obj = (RESPONSABILITE) at;
		try {
			PreparedStatement prepare = this.connect
				.prepareStatement("INSERT INTO RESPONSABILITE(responsabilite) VALUES (?)");
			prepare.setString(1, obj.getResponsabilite());
			prepare.executeUpdate();

			ResultSet result = this.connect.createStatement().executeQuery(
				"SELECT SEQ_RESP_IDRESP.currval FROM dual");
			result.first();
			long id = result.getLong("idresponsabilite");
			obj = this.find(id);

			prepare.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return obj;
	}

	@Override
	public RESPONSABILITE update(AbstractTable at) {
		RESPONSABILITE obj = (RESPONSABILITE) at;
		try {
			Statement stmt = this.connect.createStatement();
			stmt.executeUpdate("UPDATE RESPONSABILITE SET responsabilite = '"
				+ obj.getResponsabilite() + "' WHERE idresponsabilite = " + obj.getId());
			obj = this.find(obj.getId());
			stmt.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return obj;
	}

	@Override
	public RESPONSABILITE delete(AbstractTable at) {
		RESPONSABILITE obj = (RESPONSABILITE) at;
		try {
			Statement stmt = this.connect.createStatement();
			stmt.executeUpdate("DELETE FROM RESPONSABILITE WHERE idresponsabilite = " + obj.getId());
			stmt.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return obj;
	}

	@Override
	public ArrayList<RESPONSABILITE> list() {
		ArrayList<RESPONSABILITE> list = new ArrayList<RESPONSABILITE>();
		try {
			Statement stmt = this.connect.createStatement();
			ResultSet result = stmt.executeQuery("SELECT * FROM RESPONSABILITE");
			while (result.next())
				list.add(new RESPONSABILITE(result.getLong("IDRESPONSABILITE"), result
					.getString("RESPONSABILITE")));
			result.close();
			stmt.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return list;
	}
}
